package com.rollawizards.input
{
    import flash.events.Event;
    import flash.events.EventDispatcher;
    import flash.events.KeyboardEvent;
    import flash.ui.Keyboard
    import flash.display.DisplayObject;

    public class Keyboard extends EventDispatcher
    {
        private var m_UpPressed:Boolean = false;
        private var m_DownPressed:Boolean = false;
        private var m_LeftPressed:Boolean = false;
        private var m_RightPressed:Boolean = false;

        public function get upPressed():Boolean
        {
            return m_UpPressed;
        }

        public function get downPressed():Boolean
        {
            return m_DownPressed;
        }

        public function get leftPressed():Boolean
        {
            return m_LeftPressed;
        }

        public function get rightPressed():Boolean
        {
            return m_RightPressed;
        }

        public function Keyboard(displayObject:DisplayObject)
        {
            displayObject.addEventListener(KeyboardEvent.KEY_DOWN, this.onKeyDown);
            displayObject.addEventListener(KeyboardEvent.KEY_UP, this.onKeyUp);
        }

        private function setKey(code:uint, pressed:Boolean):void {
            switch (code)
            {
                case flash.ui.Keyboard.S:
                    m_DownPressed = pressed;
                    break;
                case flash.ui.Keyboard.W:
                    m_UpPressed = pressed;
                    break;
                case flash.ui.Keyboard.A:
                    m_LeftPressed = pressed;
                    break;
                case flash.ui.Keyboard.D:
                    m_RightPressed = pressed;
                    break;
                default:
                    break;
            }
        }

        private function onKeyDown(e:KeyboardEvent):void {
            setKey(e.keyCode, true);
            dispatchEvent(new InputEvent(InputEvent.KEYBOARD));
        }

        private function onKeyUp(e:KeyboardEvent):void {
            setKey(e.keyCode, false);
            dispatchEvent(new InputEvent(InputEvent.KEYBOARD));
        }
    }
}